package com.asktgapp.user.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.model.DeviceTypeVO;
import com.asktgapp.model.IndustryInfoDetailVO;
import com.asktgapp.model.RentInfoVO;
import com.asktgapp.model.SecondhandTypeVO;
import com.asktgapp.model.UsedMachineVO;
import com.asktgapp.modulebase.common.adapter.BaseAdapter;
import com.asktgapp.modulebase.common.adapter.BaseViewHolder;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.user.activity.PublishRentActicity;
import com.asktgapp.user.activity.PublishUsedMachineActivity;
import com.asktgapp.user.activity.RentDetailActivity;
import com.asktgapp.user.activity.RentMachineActivity;
import com.asktgapp.user.activity.UsedMachineActivity;
import com.asktgapp.user.activity.UsedMachineDetailActivity;
import com.asktgapp.user.activity.UsedSecondhandAllTypeActivity;
import com.asktgapp.utils.ImageDisplayUtil;
import com.asktgapp.widget.RefreshRecyclerView;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class RentMachineNewFragment extends BaseFragment {


    RecyclerView mRecyclerView;
    @InjectView(R.id.recycle)
    RefreshRecyclerView refreshRecyclerView;

    private BaseAdapter mBaseAdapter, mTypeAdapter;
    private int mPage = 1;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.freshrecyclerview, container, false);
        ButterKnife.inject(this, viewGroup);
//        EventBus.getDefault().register(this);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }


    @Override
    protected void initView(View rootView) {
        setHasOptionsMenu(true);
        getBaseActivity().setBackNavigationIcon();
        mRecyclerView = refreshRecyclerView.getRecyclerView();

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        refreshRecyclerView.setRefreshAction(new RefreshRecyclerView.Action() {
            @Override
            public void onAction(int page) {
                mPage = 1;
                getNetData(mPage);
            }
        });
        refreshRecyclerView.setLoadMoreAction(new RefreshRecyclerView.Action() {
            @Override
            public void onAction(int page) {
                mPage = page;
                getNetData(mPage);
            }
        });


        mBaseAdapter = new BaseAdapter(getActivity()) {
            @Override
            public BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {
                BaseViewHolder holder;
                if (viewType == 1) {
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_hot_equipment_type, parent, false),
                            new BaseViewHolder.Callbacks() {
                                @Override
                                public void bind(BaseViewHolder holder, Object data) {
//                                    holder.getView(R.id.).setOnClickListener(new View.OnClickListener() {
//                                        @Override
//                                        public void onClick(View v) {
//                                            Intent intent = new Intent(getActivity(), UsedMachineActivity.class);
//                                            intent.putExtra("typeId", "");
//                                            startActivity(intent);
//                                        }
//                                    });
                                    RecyclerView rvSecondhandType = holder.getView(R.id.rvSecondhandType);
                                    rvSecondhandType.setLayoutManager(new GridLayoutManager(getContext(), 2));
                                    rvSecondhandType.setAdapter(mTypeAdapter);
                                    rvSecondhandType.setNestedScrollingEnabled(false);
                                    if (hotTypeList != null) {
                                        mTypeAdapter.setData(hotTypeList);
                                    }
                                    holder.getView(R.id.allType).setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            Intent intent = new Intent(getActivity(), UsedSecondhandAllTypeActivity.class);
                                            intent.putExtra("type", 1);
                                            getActivity().startActivity(intent);
                                        }
                                    });

                                }

                                @Override
                                public void onItemClick(View view, int position) {

                                }
                            });
                } else {
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_used_machine, parent, false),
                            new BaseViewHolder.Callbacks() {
                                @Override
                                public void bind(BaseViewHolder holder, Object data) {
                                    if (data instanceof RentInfoVO.DataListBean) {
                                        RentInfoVO.DataListBean bean = (RentInfoVO.DataListBean) data;
                                        ImageView saleState = holder.getView(R.id.iv_saled);
                                        ImageView img = holder.getView(R.id.iv_machine);
                                        ImageDisplayUtil.LoadNetImageWithUrl(img, getActivity(), bean.getBanner_pic());
                                        holder.setText(R.id.tv_used_machine_name, bean.getTitle());
                                        holder.setText(R.id.detail, bean.getPro_name().replaceAll("省", "") + " " + bean.getCity_name().replaceAll("市", ""));
//                                    DecimalFormat df = new DecimalFormat("0.00");
                                        holder.setText(R.id.tv_price, Utils.D2I(bean.getPrice()) + "");
//                                    holder.setText(R.id.tvUnit, bean.getPrice_unit());
                                        Date date = Util.StrToDate(bean.getAdd_time(), "yyyy.MM.dd HH:mm:ss");
                                        String timeStr = Utils.getAskTime(date);
                                        holder.setText(R.id.addTime, timeStr);
                                        holder.setText(R.id.tvUnit, bean.getPrice_unit());
//                                    if (bean.getState() == 0) {
//                                        saleState.setVisibility(View.GONE);
//                                    } else {
//                                        saleState.setVisibility(View.VISIBLE);
//                                    }
//                                    if (bean.getState() == 0) {
//                                        holder.setText(R.id.tag, "待租");
//                                    } else {
//                                        holder.setText(R.id.tag, "忙碌");
//                                    }
                                    }


                                }

                                @Override
                                public void onItemClick(View view, int position) {
                                    RentInfoVO.DataListBean bean = (RentInfoVO.DataListBean) mBaseAdapter.getData().get(position);
                                    Intent intent = new Intent(getActivity(), RentDetailActivity.class);
                                    intent.putExtra("id", String.valueOf(bean.getIdX()));
                                    intent.putExtra("unit", bean.getPrice_unit());
                                    startActivity(intent);
                                }
                            });
                }
                return holder;
            }

            @Override
            public int getItemViewType(int position) {
                RentInfoVO.DataListBean bean = (RentInfoVO.DataListBean) mBaseAdapter.getData().get(position);
                if (Util.isEmpty(bean.getCity_name()) && Util.isEmpty(bean.getAdd_time()))
                    return 1;//头部布局
                else
                    return 2;

            }
        };

        mRecyclerView.setAdapter(mBaseAdapter);

        mTypeAdapter = new BaseAdapter(getActivity()) {
            @Override
            public BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {
                BaseViewHolder holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_secondhand_type, parent, false), new BaseViewHolder.Callbacks() {
                    @Override
                    public void bind(BaseViewHolder holder, Object data) {
                        if (data instanceof DeviceTypeVO) {
                            DeviceTypeVO bean = (DeviceTypeVO) data;
                            TextView type = holder.getView(R.id.tv_type);
                            ImageView choose = holder.getView(R.id.iv_choose);
                            type.setText(bean.getName());
                            ImageDisplayUtil.LoadNetImage(choose, getActivity(), ((DeviceTypeVO) data).getImg());
                        }

                    }

                    @Override
                    public void onItemClick(View view, int position) {
                        DeviceTypeVO bean = (DeviceTypeVO) mTypeAdapter.getData().get(position);
                        Intent intent = new Intent(getActivity(), RentMachineActivity.class);
                        intent.putExtra("typeId", bean.getId());
                        intent.putExtra("typeName", bean.getName());
                        startActivity(intent);
                    }
                });
                return holder;
            }
        };


    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.finish, menu);
        menu.getItem(0).setTitle("发布");
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
//        startActivity(new Intent(getActivity(), SearchBaseActivity.class));
//        startActivity(new Intent(getActivity(), PublishUsedMachineActivity.class));
        if (checkIsLogin("登录后可体验更多内容"))
            startActivity(new Intent(getActivity(), PublishRentActicity.class));
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void loadData() {
        visibleLoading();
//        getMachineAllType();
        getHotData();
        getNetData(mPage);
    }

    private List<DeviceTypeVO> hotTypeList;

    private void getHotData() {
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("page", 1);
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        Call<ApiResponseBody<SecondhandTypeVO>> call = apiservice.findTwoHardHotTypeList(params);
        call.enqueue(new Callback<ApiResponseBody<SecondhandTypeVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<SecondhandTypeVO>> call, Response<ApiResponseBody<SecondhandTypeVO>> response) {
                inVisibleLoading();

                if (response.isSuccessful()) {
                    SecondhandTypeVO secondhandTypeVO = response.body().getResult();
                    if (secondhandTypeVO == null)
                        return;

                    if (secondhandTypeVO.getHotTypeList().size() > 0) {
                        hotTypeList = secondhandTypeVO.getHotTypeList();
                        mTypeAdapter.setData(hotTypeList);
                    }
                } else {
                    showTost(response.message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<SecondhandTypeVO>> call, Throwable t) {
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });


    }

    private void getMachineAllType() {
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("page", 1);
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        Call<ApiResponseBody<List<DeviceTypeVO>>> call = apiservice.getMachineAllType(params);
        call.enqueue(new Callback<ApiResponseBody<List<DeviceTypeVO>>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<List<DeviceTypeVO>>> call, Response<ApiResponseBody<List<DeviceTypeVO>>> response) {
                inVisibleLoading();

                if (response.isSuccessful()) {
                    List<DeviceTypeVO> deviceTypeVOS = response.body().getResult();
                    if (deviceTypeVOS == null)
                        return;

                    if (deviceTypeVOS.size() > 0) {
                        mTypeAdapter.setData(deviceTypeVOS);
                    }

                } else {
                    showTost(response.message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<List<DeviceTypeVO>>> call, Throwable t) {
                inVisibleLoading();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });


    }

    private void getNetData(final int mPage) {
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        params.put("type", "0");
        params.put("page", mPage);

        Call<ApiResponseBody<RentInfoVO>> call = apiservice.findLeaseInfo(params);
        call.enqueue(new Callback<ApiResponseBody<RentInfoVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<RentInfoVO>> call, Response<ApiResponseBody<RentInfoVO>> response) {
                inVisibleLoading();
                if (refreshRecyclerView != null)
                    refreshRecyclerView.endPage();
                if (response.isSuccessful()) {
                    RentInfoVO secondhandTypeVO = response.body().getResult();
                    if (secondhandTypeVO == null)
                        return;
                    if (mPage == 1) {
                        if (secondhandTypeVO.getDataList().size() > 0) {
                            secondhandTypeVO.getDataList().add(0, new RentInfoVO.DataListBean());
                            mBaseAdapter.setData(secondhandTypeVO.getDataList());
                            refreshRecyclerView.showNextMore(mPage);
                        } else {
                            refreshRecyclerView.showNoMore();
                        }

                    } else {
                        if (secondhandTypeVO.getDataList().size() > 0) {
                            mBaseAdapter.addData(BaseAdapter.AddType.LASE, secondhandTypeVO.getDataList());
                            refreshRecyclerView.showNextMore(mPage);
                        } else {
                            refreshRecyclerView.showNoMore();
                        }
                    }
                } else {
                    showTost(response.message(), 1);
                }

            }

            @Override
            public void onFailure(Call<ApiResponseBody<RentInfoVO>> call, Throwable t) {
                inVisibleLoading();
                if (refreshRecyclerView != null)
                    refreshRecyclerView.endPage();

                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
//        EventBus.getDefault().unregister(this);
        ButterKnife.reset(this);

    }


}
